<template>
    <el-dialog v-model="visible" title="修改合约时间" width="360px" :close-on-click-modal="false" class="edit-endtime-dialog" draggable>
      <el-form :model="form" label-width="90px" style="width:100%;">
        <el-form-item label="客户姓名">
          <el-input v-model="form.clientName" disabled style="width:100%;" />
        </el-form-item>
        <el-form-item label="原开始时间">
          <el-input v-model="form.oldStartDate" disabled style="width:100%;" />
        </el-form-item>
        <el-form-item label="原结束时间">
          <el-input v-model="form.oldEndDate" disabled style="width:100%;" />
        </el-form-item>
        <el-form-item label="新结束日期" prop="newEndDate">
          <el-date-picker v-model="form.newEndDate" type="date" placeholder="请选择新结束日期" value-format="YYYY-MM-DD" style="width:100%;" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="visible = false" style="width:38%;">取消</el-button>
          <el-button type="primary" @click="onSubmit" style="width:38%;margin-left:6%;">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </template>
  
  <script setup>
  import { ref, defineExpose, defineEmits, inject } from 'vue'
  import { ElMessage } from 'element-plus'
  import qs from 'qs'

  const axios = inject('axios')
  
  const visible = ref(false)
  const form = ref({
    recordId: '',       // 也可能是入住记录id
    clientId: '',
    clientName: '',
    oldStartDate: '',
    oldEndDate: '',
    newEndDate: ''
  })
  const emit = defineEmits(['refresh'])
  
  // 弹窗打开并填充数据
  const open = (row) => {
    // 支持多种字段来源
    form.value.recordId = row.checkinRecord?.recordId || ''
    form.value.clientId = row.client?.clientId || ''
    form.value.clientName = row.client?.name || ''
    form.value.oldStartDate = row.bedUsage?.startDate || row.checkinRecord?.checkinDate || ''
    form.value.oldEndDate = row.bedUsage?.endDate || row.checkinRecord?.checkoutDate || ''
    form.value.newEndDate = ''
    visible.value = true
  }
  
  // 提交
  const onSubmit = async () => {
    if (!form.value.newEndDate) {
      ElMessage.warning('请选择新结束日期')
      return
    }
    try {
      let params = {
          clientId: form.value.clientId,
          contractEndDate: form.value.newEndDate
        }  
      const { data } = await axios.post('/checkinRecord/updateEndDate', qs.stringify(params))
      if (data.status === 200) {
        ElMessage.success('修改成功')
        visible.value = false
        emit('refresh')
      } else {
        ElMessage.error(data.msg || '修改失败')
      }
    } catch {
      ElMessage.error('请求失败')
    }
  }
  
  defineExpose({ open })
  </script>
  
  <style scoped>
  .edit-endtime-dialog .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 6%;
  }
  </style>
  